package adapter

import (
	"bytes"
	"errors"
	"fmt"
	"migration-tool/adapter/gitee"
	"migration-tool/target"
	"os"
	"os/exec"
	"strconv"
	"strings"
)

const (
	ImportStep = 500
)

func atomGitDealDeployKeysSetting(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitDeployKeysSettingList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameDeployKeysSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.DeployKeysList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitDeployKeysSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealWebHookSetting(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitWebHookSettingList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameWebHookSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.WebHookList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitWebHookSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealPushRuleSetting(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitPushRuleSettingList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNamePushRuleSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.PushRuleSettingList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitPushRuleSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealCodeReviewSetting(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitCodeReviewSetting
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameCodeReviewSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitCodeReviewSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealProtectBranchSetting(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitProtectBranchSettingList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameProtectBranchSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.ProtectBranchSettingList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitProtectBranchSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealRepoMetaInfo(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitRepoMetaInfo
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMetaInfo,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	//data.PathWithNamespace = "openEuler/" + data.Path
	//data.Namespace.Id = 5161228
	//data.Namespace.Name = "openEuler"
	//data.Namespace.Path = "openeuler"
	//data.Namespace.CompleteName = "openEuler"
	//data.Namespace.CompletePath = "openeuler"

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitRepoMetaInfo(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func atomGitDealRepoMember(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitRepoMemberList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMembers,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.MemberList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitRepoMembers(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealRelease(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitReleaseList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameReleases,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.ReleaseList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitRelease(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealMileStone(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitMileStoneList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameMileStones,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.MileStoneList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitMilestone(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}
	return nil
}

func atomGitDealMergeRequest(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}

	var fileName string
	if args.IncrementFlag {
		fileName = BinFileNameMergeRequestsIncrement
	} else {
		fileName = BinFileNameMergeRequests
	}

	var data target.AtomGitMergeRequestList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           fileName,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	//crossRepoPath := "/Users/buyu/test/my_repo_data/mr-cross.data"
	//sameRepoPath := "/Users/buyu/test/my_repo_data/mr-same.data"
	//var crossData target.AtomGitMergeRequestList
	//var sameData target.AtomGitMergeRequestList
	//sameData.RepoId = data.RepoId
	//sameData.RepoName = data.RepoName
	//sameData.RepoGroupName = data.RepoGroupName
	//crossData.RepoId = data.RepoId
	//crossData.RepoName = data.RepoName
	//crossData.RepoGroupName = data.RepoGroupName
	//crossCnt := 0
	//sameCnt := 0
	//edge := 100
	//
	//for _, val := range data.MergeRequestList {
	//	if val.SourceRepoPath == val.TargetRepoPath && sameCnt < edge && val.SourceRepoPath != "" && val.TargetRepoPath != "" {
	//		sameData.MergeRequestList = append(sameData.MergeRequestList, val)
	//		sameCnt++
	//	} else if val.SourceRepoPath != val.TargetRepoPath && crossCnt < edge && val.SourceRepoPath != "" && val.TargetRepoPath != "" {
	//		crossData.MergeRequestList = append(crossData.MergeRequestList, val)
	//		crossCnt++
	//	}
	//	//for _, cmt := range val.CommentList {
	//	//	if cnt == 0 && cmt.FilePath != "" && val.Id != 2896102 {
	//	//		fmt.Println(val.String())
	//	//		cnt++
	//	//	}
	//	//}
	//
	//}
	//if len(crossData.MergeRequestList) > 0 {
	//	byteArr, err := proto.Marshal(&crossData)
	//	if err = os.WriteFile(crossRepoPath, byteArr, os.ModePerm); err != nil {
	//	}
	//	fmt.Println("跨库写入成功")
	//}
	//if len(sameData.MergeRequestList) > 0 {
	//	byteArr, err := proto.Marshal(&sameData)
	//	if err = os.WriteFile(sameRepoPath, byteArr, os.ModePerm); err != nil {
	//	}
	//	fmt.Println("同库写入成功")
	//}
	//
	//filepathRepoPath := "/Users/buyu/test/my_repo_data/mr-filepath.data"
	//filepathRepoPath := "/Users/buyu/test/my_repo_data/mr-failed.data"
	//var filepathData target.AtomGitMergeRequestList
	//filepathData.RepoId = data.RepoId
	//filepathData.RepoName = data.RepoName
	//filepathData.RepoGroupName = data.RepoGroupName
	////filepathCnt := 0
	////filepathEdge := 5
	//
	//for _, val := range data.MergeRequestList {
	//	//if val.SourceRepoPath == val.TargetRepoPath && filepathCnt < filepathEdge && val.SourceRepoPath != "" && val.TargetRepoPath != "" {
	//	//	for _, cmt := range val.CommentList {
	//	//		if cmt.FilePath != "" {
	//	//			filepathData.MergeRequestList = append(filepathData.MergeRequestList, val)
	//	//			filepathCnt++
	//	//			break
	//	//		}
	//	//	}
	//	//}
	//	if val.Id == 3148340 {
	//		filepathData.MergeRequestList = append(filepathData.MergeRequestList, val)
	//		break
	//	}
	//}
	//if len(filepathData.MergeRequestList) > 0 {
	//	byteArr, err := proto.Marshal(&filepathData)
	//	if err = os.WriteFile(filepathRepoPath, byteArr, os.ModePerm); err != nil {
	//	}
	//	fmt.Println("代码评论的mr写入成功")
	//	return nil
	//}
	//
	//cnt := 0
	//for _, val := range data.MergeRequestList {
	//	if val.Id == 3148340 {
	//		fmt.Println(val.String())
	//	}
	//}

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.MergeRequestList) {
		right := left + ImportStep

		var mrData target.AtomGitMergeRequestList
		mrData.RepoId = data.RepoId
		mrData.RepoName = data.RepoName
		mrData.RepoGroupName = data.RepoGroupName
		if right > len(data.MergeRequestList) {
			right = len(data.MergeRequestList)
		}
		if left >= right {
			break
		}

		mrData.MergeRequestList = append(mrData.MergeRequestList, data.MergeRequestList[left:right]...)

		//for idx := range mrData.MergeRequestList {
		//	mrData.MergeRequestList[idx].Body = "xxx"
		//	mrData.MergeRequestList[idx].Title = "123"
		//}

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitRepoServiceClient(args.Conn)
		resp, err := client.ImportAtomGitMergeRequest(ctx, &mrData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}

		recordArgs.Msg = "已成功导入" + strconv.Itoa(right) + "条Mr数据"
		recordTask(recordArgs)

		left += ImportStep
	}
	return nil
}

func atomGitDealIssue(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitIssueList

	var fileName string
	if args.IncrementFlag {
		fileName = BinFileNameIssuesIncrement
	} else {
		fileName = BinFileNameIssues
	}

	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           fileName,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	//filePath := "/Users/buyu/test/my_repo_data/issue-failed.data"
	//var fileData target.AtomGitIssueList
	//fileData.RepoId = data.RepoId
	//fileData.RepoName = data.RepoName
	//fileData.RepoGroupName = data.RepoGroupName
	//for _, val := range data.IssueList {
	//	if val.Number == "I6ACIY" {
	//		fileData.IssueList = append(fileData.IssueList, val)
	//	}
	//}
	//if len(fileData.IssueList) > 0 {
	//	fmt.Println(len(fileData.IssueList))
	//	byteArr, err := proto.Marshal(&fileData)
	//	if err = os.WriteFile(filePath, byteArr, os.ModePerm); err != nil {
	//	}
	//	fmt.Println("错误写入成功")
	//}

	//for _, val := range data.IssueList {
	//	if val.Number == "I6ACIY" {
	//		fmt.Println(val.String())
	//		return nil
	//	}
	//}

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.IssueList) {
		right := left + ImportStep

		var issueData target.AtomGitIssueList
		issueData.RepoId = data.RepoId
		issueData.RepoName = data.RepoName
		issueData.RepoGroupName = data.RepoGroupName
		if right > len(data.IssueList) {
			right = len(data.IssueList)
		}
		if left >= right {
			break
		}
		issueData.IssueList = append(issueData.IssueList, data.IssueList[left:right]...)

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
		resp, err := client.ImportAtomGitIssue(ctx, &issueData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}
		recordArgs.Msg = "已成功导入" + strconv.Itoa(right) + "条Issue数据"
		recordTask(recordArgs)

		left += ImportStep
	}

	return nil
}

func atomGitDealCode(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitRepoMetaInfo
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMetaInfo,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	readDataArgs = DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FilePathTmpl:       CloneRepoFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               nil,
	}

	dir, err := MkdirFromStringTmpl(readDataArgs)
	if err != nil {
		return err
	}

	_, err = os.Stat(dir)
	if os.IsNotExist(err) {
		return errors.New("仓库代码不存在")
	} else if err != nil {
		return err
	}
	//
	//data.PathWithNamespace = "openEuler/" + data.Path
	//data.Namespace.Id = 5161228
	//data.Namespace.Name = "openEuler"
	//data.Namespace.Path = "openeuler"
	//data.Namespace.CompleteName = "openEuler"
	//data.Namespace.CompletePath = "openeuler"

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitInitRepo(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	//recordArgs.Msg = "push-url-【" + resp.RepoHttpCloneUrl + "】"
	//recordTask(recordArgs)

	var cmd *exec.Cmd
	//cmd = exec.Command("git", "-C", dir, "push", "--mirror", resp.RepoHttpCloneUrl)
	cmd = exec.Command("git", "-C", dir, "-c", "push.negotiate=true", "push", "--mirror", resp.RepoHttpCloneUrl)
	combinedOutput, err := cmd.CombinedOutput()
	if err != nil {
		recordArgs.Msg = string(combinedOutput)
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	recordArgs.Msg = "仓库推送成功"
	recordTask(recordArgs)
	return nil
}

func atomGitDealWiki(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitRepoMetaInfo
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMetaInfo,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	readDataArgs = DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FilePathTmpl:       CloneWikiFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               nil,
	}

	dir, err := MkdirFromStringTmpl(readDataArgs)
	if err != nil {
		return err
	}

	_, err = os.Stat(dir)
	if os.IsNotExist(err) {
		recordArgs.Msg = "仓库wiki不存在"
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitInitRepo(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	idx := strings.LastIndex(resp.RepoHttpCloneUrl, ".git")
	wikiUrl := strings.Replace(resp.RepoHttpCloneUrl, ".git", ".wiki.git", idx)

	var cmd *exec.Cmd
	//cmd = exec.Command("git", "-C", dir, "push", "--mirror", resp.RepoHttpCloneUrl)
	cmd = exec.Command("git", "-C", dir, "-c", "push.negotiate=true", "push", "--mirror", wikiUrl)
	if err = cmd.Run(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	recordArgs.Msg = "wiki推送成功"
	recordTask(recordArgs)
	return nil
}

func globalAtomGitDealLabel(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitLabelList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameLabels,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.LabelList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	// atomgit实现的label需要去重逻辑，按照name作为唯一的key
	var deDuplicationData target.AtomGitLabelList
	nameMap := make(map[string]struct{})
	deDuplicationData.GroupPathList = data.GroupPathList
	for _, val := range data.LabelList {
		lowerCase := strings.ToLower(val.Name)
		if _, ok := nameMap[lowerCase]; !ok {
			deDuplicationData.LabelList = append(deDuplicationData.LabelList, val)
			nameMap[lowerCase] = struct{}{}
		}
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitLabel(ctx, &deDuplicationData)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func globalAtomGitDealEnterprise(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var enterprise target.AtomGitEnterprise
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameEnterprise,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &enterprise,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitEnterprise(ctx, &enterprise)
	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func globalAtomGitDealEnterpriseMember(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}

	var member target.AtomGitEnterpriseMemberList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameEnterpriseMembersProto,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &member,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitEnterpriseMember(ctx, &member)
	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func globalAtomGitDealUser(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitUserList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameAllUsersProto,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.UserList) {
		right := left + ImportStep

		var userData target.AtomGitUserList
		if right > len(data.UserList) {
			right = len(data.UserList)
		}
		if left >= right {
			break
		}

		userData.UserList = append(userData.UserList, data.UserList[left:right]...)

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
		resp, err := client.ImportAtomGitUser(ctx, &userData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}
		recordArgs.Msg = "已成功导入" + strconv.Itoa(right) + "条User数据"
		recordTask(recordArgs)

		left += ImportStep
	}
	return nil
}

func globalAtomGitDealGroup(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}

	var group target.AtomGitGroupList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameGroups,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &group,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitServiceClient(args.Conn)
	resp, err := client.ImportAtomGitGroup(ctx, &group)
	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func globalAtomGitDealGroupMember(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}

	var data target.AtomGitGroupMemberList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameGroupMembers,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	//for _, val := range member.MemberList {
	//	if val.User.UserName == "duan_pj" {
	//		fmt.Println(val.String())
	//	}
	//}
	//return nil

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.ImportAtomGitGroupMember(ctx, &data)
	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	return nil
}

func checkRepoCodeConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}

	// gitee部分数据
	var giteeOutput bytes.Buffer

	giteeLsRemote := exec.Command("git", "ls-remote", args.RepoInfo.CodeCloneHttpUrl)
	giteeLsRemote.Stdout = &giteeOutput

	if err := giteeLsRemote.Start(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	if err := giteeLsRemote.Wait(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	giteeRefsMap := make(map[string]string)
	for _, val := range strings.Split(giteeOutput.String(), "\n") {
		if len(val) == 0 {
			continue
		}
		arr := strings.Split(val, "\t")
		if len(arr) != 2 {
			continue
		}
		giteeRefsMap[arr[1]] = arr[0]
	}

	// atomgit的数据
	var data target.AtomGitRepoMetaInfo
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMetaInfo,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitRepo(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	var atomgitOutput bytes.Buffer
	atomGitLsRemote := exec.Command("git", "ls-remote", resp.RepoHttpCloneUrl)
	atomGitLsRemote.Stdout = &atomgitOutput

	if err = atomGitLsRemote.Start(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	if err = atomGitLsRemote.Wait(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	atomgitRefsMap := make(map[string]string)
	for _, val := range strings.Split(atomgitOutput.String(), "\n") {
		if len(val) == 0 {
			continue
		}
		arr := strings.Split(val, "\t")
		if len(arr) != 2 {
			continue
		}
		atomgitRefsMap[arr[1]] = arr[0]
	}

	equals := true
	for refName, CommitId := range giteeRefsMap {
		if atomgitRefsMap[refName] != CommitId {
			equals = false
			break
		}
	}

	if equals {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	} else {
		return errors.New(ErrorMsgCheckError)
	}

	return nil
}

func checkRepoWikiConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}

	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FilePathTmpl:       CloneWikiFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               nil,
	}

	dir, err := MkdirFromStringTmpl(readDataArgs)
	if err != nil {
		return err
	}

	_, err = os.Stat(dir)
	if os.IsNotExist(err) {
		recordArgs.Msg = "仓库wiki不存在"
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	idx := strings.LastIndex(args.RepoInfo.CodeCloneHttpUrl, ".git")
	wikiUrl := strings.Replace(args.RepoInfo.CodeCloneHttpUrl, ".git", ".wiki.git", idx)

	// gitee部分数据
	var giteeOutput bytes.Buffer
	giteeLsRemote := exec.Command("git", "ls-remote", wikiUrl)
	giteeLsRemote.Stdout = &giteeOutput
	fmt.Println(giteeLsRemote.String())
	if err := giteeLsRemote.Start(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	if err := giteeLsRemote.Wait(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	giteeRefsMap := make(map[string]string)
	for _, val := range strings.Split(giteeOutput.String(), "\n") {
		if len(val) == 0 {
			continue
		}
		arr := strings.Split(val, "\t")
		if len(arr) != 2 {
			continue
		}
		giteeRefsMap[arr[1]] = arr[0]
	}

	// atomgit的数据
	var data target.AtomGitRepoMetaInfo
	readDataArgs = DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMetaInfo,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err = ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitRepo(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	var atomgitOutput bytes.Buffer
	idx = strings.LastIndex(resp.RepoHttpCloneUrl, ".git")
	wikiUrl = strings.Replace(resp.RepoHttpCloneUrl, ".git", ".wiki.git", idx)
	atomGitLsRemote := exec.Command("git", "ls-remote", wikiUrl)
	atomGitLsRemote.Stdout = &atomgitOutput

	if err = atomGitLsRemote.Start(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	if err = atomGitLsRemote.Wait(); err != nil {
		recordArgs.Err = err
		recordTask(recordArgs)
		return err
	}

	atomgitRefsMap := make(map[string]string)
	for _, val := range strings.Split(atomgitOutput.String(), "\n") {
		if len(val) == 0 {
			continue
		}
		arr := strings.Split(val, "\t")
		if len(arr) != 2 {
			continue
		}
		atomgitRefsMap[arr[1]] = arr[0]
	}

	equals := true
	for refName, CommitId := range giteeRefsMap {
		if atomgitRefsMap[refName] != CommitId {
			equals = false
			break
		}
	}

	if equals {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	} else {
		return errors.New(ErrorMsgCheckError)
	}

	return nil
}

func equalsRepoMetaInfo(ourData *target.AtomGitRepoMetaInfo, giteeData *target.AtomGitRepoMetaInfo) bool {
	if ourData.Id != giteeData.Id ||
		ourData.Name != giteeData.Name ||
		ourData.Path != giteeData.Path ||
		ourData.PathWithNamespace != giteeData.PathWithNamespace ||
		ourData.NameWithNamespace != giteeData.NameWithNamespace ||
		ourData.Description != giteeData.Description ||
		ourData.Public != giteeData.Public {
		//ourData.DefaultBranch != giteeData.DefaultBranch ||
		//ourData.OrganizationId != giteeData.OrganizationId ||
		//ourData.CreatedAt != giteeData.CreatedAt ||
		//ourData.UpdatedAt != giteeData.UpdatedAt ||
		//ourData.Namespace.Id != giteeData.Namespace.Id ||
		//ourData.Namespace.Name != giteeData.Namespace.Name ||
		//ourData.Creator.Id != giteeData.Creator.Id ||
		//ourData.Creator.Name != giteeData.Creator.Name ||
		//ourData.Creator.UserName != giteeData.Creator.UserName ||
		//ourData.Creator.Phone != giteeData.Creator.Phone ||
		//ourData.Creator.Email != giteeData.Creator.Email
		return false
	}
	return true
}

func checkRepoMetaInfoConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}

	userDetailArgs := giteeUserDetailArgs{
		Token:           args.Token,
		EnterpriseToken: args.EnterpriseToken,
		EnterpriseId:    args.RepoInfo.EnterpriseId,
	}

	tmplArgs := TmplArgs{
		RepoGroupName: args.RepoInfo.RepoGroupName,
		RepoName:      args.RepoInfo.RepoName,
		Token:         args.Token,
		StringTmpl:    GiteeV5OpenApiGetRepoMetaInfo,
	}
	realUrl, err := FillParamIntoStringTmpl(tmplArgs)
	if err != nil {
		return err
	}

	var v5data gitee.Repository
	requestArgs := giteeRequestArgs{
		RequestArgs: RequestArgs{
			ExportPlatformName: GiteePlatformName,
			RealUrl:            realUrl,
			RetVal:             &v5data,
		},
		TaskName: args.TaskName,
		Log:      args.Log,
	}
	if err = giteeDoGetRequest(requestArgs); err != nil {
		return err
	}

	tmplArgs = TmplArgs{
		EnterpriseId:    args.RepoInfo.EnterpriseId,
		RepoId:          args.RepoInfo.RepoId,
		EnterpriseToken: args.EnterpriseToken,
		StringTmpl:      GiteeV8OpenApiGetRepoDetail,
	}
	realUrl, err = FillParamIntoStringTmpl(tmplArgs)
	if err != nil {
		return err
	}
	var v8data gitee.V8RepositoryDetail
	requestArgs = giteeRequestArgs{
		RequestArgs: RequestArgs{
			ExportPlatformName: GiteePlatformName,
			RealUrl:            realUrl,
			RetVal:             &v8data,
		},
		TaskName: args.TaskName,
		Log:      args.Log,
	}
	if err = giteeDoGetRequest(requestArgs); err != nil && args.EnterpriseToken != "" {
		return err
	}

	var giteeMetaInfo target.AtomGitRepoMetaInfo
	var giteeNamespace target.AtomGitNamespace
	giteeMetaInfo.Namespace = &giteeNamespace

	var creator target.AtomGitUser
	creator.Id = v5data.Owner.ID
	creator.Name = v5data.Owner.Name
	creator.UserName = v5data.Owner.Login
	userDetailArgs.User = &creator
	err = giteeV8GetUserDetail(userDetailArgs)
	if err != nil {
		_ = giteeGetUserDetail(userDetailArgs)
	}
	giteeMetaInfo.Creator = &creator
	giteeMetaInfo.OrganizationId = args.RepoInfo.EnterpriseId

	copyMetaInfoFromV5Data(&giteeMetaInfo, &v5data)
	copyMetaInfoFromV8Data(&giteeMetaInfo, &v8data)

	var readData target.AtomGitRepoMetaInfo
	var OurData *target.AtomGitRepoMetaInfo

	dataArgs := DataArgs{
		RepoInfo:           args.RepoInfo,
		ExportDataDir:      args.ExportDataDir,
		FileName:           BinFileNameRepoMetaInfo,
		ExportPlatformName: GiteePlatformName,
		FilePathTmpl:       ExportDataFileTmpl,
		Data:               &readData,
	}
	OurData = &readData
	_, err = ReadProtoData(dataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitRepoMetaInfo(ctx, &readData)

	if err != nil {
		return err
	}

	if !resp.Success {
		return errors.New(ErrorMsgRpcResponseError + "TraceId为:" + resp.TraceId)
	}
	OurData = resp.MetaInfo
	if equalsRepoMetaInfo(OurData, &giteeMetaInfo) {
		recordArgs.Msg = LogMsgCheckSuccess
	} else {
		recordArgs.Err = errors.New("AtomGit数据为:【" + OurData.String() + "】")
		recordTask(recordArgs)

		recordArgs.Err = errors.New("Gitee数据为:【" + giteeMetaInfo.String() + "】")
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	}

	return nil
}

func checkRepoMemberConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitRepoMemberList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameRepoMembers,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.MemberList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitRepoMembers(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedId) > 0 {
		dataIdMap := make(map[int64]*target.AtomGitMember)
		for _, val := range data.MemberList {
			dataIdMap[val.User.Id] = val
		}

		var failedImportData target.AtomGitRepoMemberList
		failedImportData.RepoId = data.RepoId
		failedImportData.RepoName = data.RepoName
		failedImportData.RepoGroupName = data.RepoGroupName

		for _, val := range resp.FailedId {
			failedImportData.MemberList = append(failedImportData.MemberList, dataIdMap[val])
		}

		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameRepoMembersFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.MemberList)) + "条导入失败的仓库成员数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.MemberList)) + "条导入失败的仓库成员数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkProtectBranchSettingConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitProtectBranchSettingList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameProtectBranchSetting,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.ProtectBranchSettingList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitProtectBranchSetting(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedBranchPattern) > 0 {
		dataIdMap := make(map[string]*target.AtomGitProtectBranchSetting)
		for _, val := range data.ProtectBranchSettingList {
			dataIdMap[val.BranchPattern] = val
		}

		var failedImportData target.AtomGitProtectBranchSettingList
		failedImportData.RepoId = data.RepoId
		failedImportData.RepoName = data.RepoName
		failedImportData.RepoGroupName = data.RepoGroupName
		failedImportData.DefaultBranch = data.DefaultBranch
		for _, val := range resp.FailedBranchPattern {
			failedImportData.ProtectBranchSettingList = append(failedImportData.ProtectBranchSettingList, dataIdMap[val])
		}

		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameProtectBranchSettingFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.ProtectBranchSettingList)) + "条导入失败的保护分支数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.ProtectBranchSettingList)) + "条导入失败的保护分支数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkReleaseConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitReleaseList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameReleases,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.ReleaseList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitRelease(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedId) > 0 {
		dataIdMap := make(map[int64]*target.AtomGitRelease)
		for _, val := range data.ReleaseList {
			dataIdMap[val.Id] = val
		}

		var failedImportData target.AtomGitReleaseList
		failedImportData.RepoId = data.RepoId
		failedImportData.RepoName = data.RepoName
		failedImportData.RepoGroupName = data.RepoGroupName

		for _, val := range resp.FailedId {
			failedImportData.ReleaseList = append(failedImportData.ReleaseList, dataIdMap[val])
		}

		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameReleasesFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.ReleaseList)) + "条导入失败的release数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.ReleaseList)) + "条导入失败的release数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkMileStoneConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitMileStoneList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameMileStones,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.MileStoneList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitMilestone(ctx, &data)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedId) > 0 {
		dataIdMap := make(map[int64]*target.AtomGitMileStone)
		for _, val := range data.MileStoneList {
			dataIdMap[val.Id] = val
		}

		var failedImportData target.AtomGitMileStoneList
		failedImportData.RepoId = data.RepoId
		failedImportData.RepoName = data.RepoName
		failedImportData.RepoGroupName = data.RepoGroupName

		for _, val := range resp.FailedId {
			failedImportData.MileStoneList = append(failedImportData.MileStoneList, dataIdMap[val])
		}

		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameMileStonesFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.MileStoneList)) + "条导入失败的milestone数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.MileStoneList)) + "条导入失败的milestone数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkMergeRequestConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}

	var fileName string
	if args.IncrementFlag {
		fileName = BinFileNameMergeRequestsIncrement
	} else {
		fileName = BinFileNameMergeRequests
	}

	var data target.AtomGitMergeRequestList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           fileName,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	dataIdMap := make(map[int64]*target.AtomGitMergeRequest)
	for _, val := range data.MergeRequestList {
		dataIdMap[val.Id] = val
	}

	var failedImportData target.AtomGitMergeRequestList
	failedImportData.RepoId = data.RepoId
	failedImportData.RepoName = data.RepoName
	failedImportData.RepoGroupName = data.RepoGroupName

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.MergeRequestList) {
		right := left + ImportStep

		var mrData target.AtomGitMergeRequestList
		mrData.RepoId = data.RepoId
		mrData.RepoName = data.RepoName
		mrData.RepoGroupName = data.RepoGroupName
		if right > len(data.MergeRequestList) {
			right = len(data.MergeRequestList)
		}
		if left >= right {
			break
		}

		mrData.MergeRequestList = append(mrData.MergeRequestList, data.MergeRequestList[left:right]...)

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitRepoServiceClient(args.Conn)
		resp, err := client.CheckAtomGitMergeRequest(ctx, &mrData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}

		if args.Write {
			for _, val := range resp.FailedId {
				failedImportData.MergeRequestList = append(failedImportData.MergeRequestList, dataIdMap[val])
			}
		}

		recordArgs.Msg = "已校验" + strconv.Itoa(right) + "条Mr数据"
		recordTask(recordArgs)

		left += ImportStep
	}

	if len(failedImportData.MergeRequestList) > 0 {
		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameMergeRequestsFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}
			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.MergeRequestList)) + "条导入失败的Mr数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.MergeRequestList)) + "条导入失败的Mr数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkIssueConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitIssueList

	var fileName string
	if args.IncrementFlag {
		fileName = BinFileNameIssuesIncrement
	} else {
		fileName = BinFileNameIssues
	}

	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           fileName,
		FilePathTmpl:       ExportDataFileTmpl,
		RepoInfo:           args.RepoInfo,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	dataIdMap := make(map[int64]*target.AtomGitIssue)
	for _, val := range data.IssueList {
		dataIdMap[val.Id] = val
	}

	var failedImportData target.AtomGitIssueList
	failedImportData.RepoId = data.RepoId
	failedImportData.RepoName = data.RepoName
	failedImportData.RepoGroupName = data.RepoGroupName

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.IssueList) {
		right := left + ImportStep

		var issueData target.AtomGitIssueList
		issueData.RepoId = data.RepoId
		issueData.RepoName = data.RepoName
		issueData.RepoGroupName = data.RepoGroupName
		if right > len(data.IssueList) {
			right = len(data.IssueList)
		}
		if left >= right {
			break
		}

		issueData.IssueList = append(issueData.IssueList, data.IssueList[left:right]...)

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
		resp, err := client.CheckAtomGitIssue(ctx, &issueData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}

		if args.Write {
			for _, val := range resp.FailedId {
				failedImportData.IssueList = append(failedImportData.IssueList, dataIdMap[val])
			}
		}

		recordArgs.Msg = "已校验" + strconv.Itoa(right) + "条Issue数据"
		recordTask(recordArgs)

		left += ImportStep
	}

	if len(failedImportData.IssueList) > 0 {
		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				FileName:           BinFileNameIssuesFailedImport,
				ExportPlatformName: args.ExportPlatformName,
				FilePathTmpl:       ExportDataFileTmpl,
				RepoInfo:           args.RepoInfo,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.IssueList)) + "条导入失败的Issue数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.IssueList)) + "条导入失败的Issue数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkLabelConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}
	var data target.AtomGitLabelList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameLabels,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) || len(data.LabelList) == 0 {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	// atomgit实现的label需要去重逻辑，按照name作为唯一的key
	var deDuplicationData target.AtomGitLabelList
	nameMap := make(map[string]struct{})
	deDuplicationData.GroupPathList = data.GroupPathList
	for _, val := range data.LabelList {
		lowerCase := strings.ToLower(val.Name)
		if _, ok := nameMap[lowerCase]; !ok {
			deDuplicationData.LabelList = append(deDuplicationData.LabelList, val)
			nameMap[lowerCase] = struct{}{}
		}
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitLabel(ctx, &deDuplicationData)

	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedId) > 0 {
		dataIdMap := make(map[int64]*target.AtomGitLabel)
		for _, val := range data.LabelList {
			dataIdMap[val.Id] = val
		}

		var failedImportData target.AtomGitLabelList
		failedImportData.GroupPathList = data.GroupPathList
		for _, val := range resp.FailedId {
			failedImportData.LabelList = append(failedImportData.LabelList, dataIdMap[val])
		}
		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameLabelsFailedImportProto,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			writeDataArgs = DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameLabelsFailedImportJson,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
				WriteJson:          true,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.LabelList)) + "条导入失败的Label数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.LabelList)) + "条导入失败的Label数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkGroupMemberConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
		Check:    true,
	}

	var data target.AtomGitGroupMemberList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameGroupMembers,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	ctx := GetAuthContext(args.AppKey, args.AppSecret)
	client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
	resp, err := client.CheckAtomGitGroupMember(ctx, &data)
	if err != nil {
		return err
	}

	if !resp.Success {
		recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
		recordTask(recordArgs)
		return errors.New(ErrorMsgRpcResponseError + resp.Msg)
	}

	if len(resp.FailedDataList) > 0 {
		var failedImportData target.AtomGitGroupMemberList
		for _, val := range resp.FailedDataList {
			failedImportData.MemberList = append(failedImportData.MemberList, val)
		}

		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameGroupMembersFailedImportProto,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			writeDataArgs = DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameGroupMembersFailedImportJson,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
				WriteJson:          true,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.MemberList)) + "条导入失败的groupMember数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.MemberList)) + "条导入失败的groupMember数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}

func checkUserConsistent(args TaskArgs) error {
	recordArgs := RecordArgs{
		Log:      args.Log,
		TaskName: args.TaskName,
		Err:      nil,
		Export:   false,
	}
	var data target.AtomGitUserList
	readDataArgs := DataArgs{
		ExportDataDir:      args.ExportDataDir,
		ExportPlatformName: args.ExportPlatformName,
		FileName:           BinFileNameAllUsersProto,
		EnterpriseName:     args.EnterpriseName,
		FilePathTmpl:       ExportEnterpriseFileTmpl,
		Data:               &data,
	}
	_, err := ReadProtoData(readDataArgs)
	if os.IsNotExist(err) {
		recordArgs.Msg = FileNotExist
		recordTask(recordArgs)
		return nil
	} else if err != nil {
		return err
	}

	dataIdMap := make(map[int64]*target.AtomGitUser)
	for _, val := range data.UserList {
		dataIdMap[val.Id] = val
	}

	var failedImportData target.AtomGitUserList

	// 这里由于数据量可能非常大，因此可能需要分批调用
	left := 0
	for left < len(data.UserList) {
		right := left + ImportStep

		var userData target.AtomGitUserList
		if right > len(data.UserList) {
			right = len(data.UserList)
		}
		if left >= right {
			break
		}

		userData.UserList = append(userData.UserList, data.UserList[left:right]...)

		ctx := GetAuthContext(args.AppKey, args.AppSecret)
		client := target.NewAtomGitCSDNRepoServiceClient(args.Conn)
		resp, err := client.CheckAtomGitUser(ctx, &userData)
		if err != nil {
			return err
		}

		if !resp.Success {
			recordArgs.Msg = resp.Msg + ";traceId: " + resp.TraceId
			recordTask(recordArgs)
			return errors.New(ErrorMsgRpcResponseError + resp.Msg)
		}

		if args.Write {
			for _, val := range resp.FailedId {
				failedImportData.UserList = append(failedImportData.UserList, dataIdMap[val])
			}
		}
		recordArgs.Msg = "已校验" + strconv.Itoa(right) + "条User数据"
		recordTask(recordArgs)

		left += ImportStep
	}

	if len(failedImportData.UserList) > 0 {
		if args.Write {
			writeDataArgs := DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameAllUsersFailedImportProto,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			writeDataArgs = DataArgs{
				ExportDataDir:      args.ExportDataDir,
				ExportPlatformName: args.ExportPlatformName,
				FileName:           BinFileNameAllUsersFailedImportJson,
				EnterpriseName:     args.EnterpriseName,
				FilePathTmpl:       ExportEnterpriseFileTmpl,
				Data:               &failedImportData,
				WriteJson:          true,
			}

			_, err = WriteProtoData(writeDataArgs)
			if err != nil {
				return err
			}

			recordArgs.Msg = "共落盘" + strconv.Itoa(len(failedImportData.UserList)) + "条导入失败的用户数据消息"
		} else {
			recordArgs.Msg = "共" + strconv.Itoa(len(failedImportData.UserList)) + "条导入失败的用户数据消息，数据未落盘"
		}
		recordTask(recordArgs)
		return errors.New(ErrorMsgCheckError)
	} else {
		recordArgs.Msg = LogMsgCheckSuccess
		recordTask(recordArgs)
	}

	return nil
}
